//
//  RegistViewController.swift
//  微信Swift
//
//  Created by ztDev on 15/10/7.
//  Copyright © 2015年 CC. All rights reserved.
//

import UIKit

class RegistViewController: UITableViewController {

    // 必填的textfield
    @IBOutlet var musetFillOut: [UITextField]!
    
    // 用户名
    @IBOutlet weak var userName: UITextBox!
    // 密码
    @IBOutlet weak var passworld: UITextBox!
    // 邮箱
    @IBOutlet weak var email: UITextBox!
    // 地区
    @IBOutlet weak var region: UITextBox!
    // 密码提示问题
    @IBOutlet weak var question: UITextBox!
    // 答案
    @IBOutlet weak var answer: UITextBox!
    
    var possibleInputs : Inputs = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 显示导航栏
        self.navigationController?.navigationBarHidden = false
        // 默认完成不可点
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        // 输入的时候校验
        
        // 添加用户名校验
        let userNm = AJWValidator(type: .String)
        userNm.addValidationToEnsureMinimumLength(3, invalidMessage: "用户名至少3位")
        userNm.addValidationToEnsureMaximumLength(15, invalidMessage: "最大15位")
        self.userName.ajw_attachValidator(userNm)
        
        userNm.validatorStateChangedHandler = { (newState: AJWValidatorState) -> Void in
            switch newState {
                
            case .ValidationStateValid:
                self.userName.highlightState = .Default
                self.possibleInputs.unionInPlace(Inputs.user)
                
            default:
                let errorMsg = userNm.errorMessages.first as? String
                self.userName.highlightState = UITextBoxHighlightState.Wrong(errorMsg!)
                
                self.possibleInputs.subtractInPlace(Inputs.user)
            }
            
            self.navigationItem.rightBarButtonItem?.enabled = self.possibleInputs.isAllOK()
            
        }
        
        // 添加密码校验
        let passWr = AJWValidator(type: .String)
        passWr.addValidationToEnsureMinimumLength(3, invalidMessage: "密码至少3位")
        passWr.addValidationToEnsureMaximumLength(15, invalidMessage: "最长15位")
        self.passworld.ajw_attachValidator(passWr)
        
        passWr.validatorStateChangedHandler = {(newState: AJWValidatorState) -> Void in
            switch newState {
                
            case .ValidationStateValid:
                self.passworld.highlightState = .Default
                self.possibleInputs.unionInPlace(Inputs.pass)
                
            default:
                let errorMsg = passWr.errorMessages.first as? String
                self.passworld.highlightState = UITextBoxHighlightState.Wrong(errorMsg!)
                self.possibleInputs.subtractInPlace(Inputs.pass)
            }
            self.navigationItem.rightBarButtonItem?.enabled = self.possibleInputs.boolValue
            
        }
        
        // 添加邮箱校验
        let mail = AJWValidator(type: .String)
        mail.addValidationToEnsureValidEmailWithInvalidMessage("Email格式不对")
        self.email.ajw_attachValidator(mail)
        
        mail.validatorStateChangedHandler = {(newState: AJWValidatorState) -> Void in
            switch newState {
                
            case .ValidationStateValid:
                self.email.highlightState = .Default
                self.possibleInputs.unionInPlace(Inputs.mail)
            default:
                let errorMsg = mail.errorMessages.first as? String
                self.email.highlightState = UITextBoxHighlightState.Wrong(errorMsg!)
                self.possibleInputs.subtractInPlace(Inputs.mail)
                
            }
            self.navigationItem.rightBarButtonItem?.enabled = self.possibleInputs.boolValue
            
        }
        
    }

    // 完成按钮点击事件, 注册用户
    @IBAction func done(sender: UIBarButtonItem) {
        
        //显示一个载入提示
        self.pleaseWait()
        
        //建立用户的 AVObject
        let user = AVObject(className: "XBUser")
        
        //把输入的文本框的值，设置到对象中
        user["user"] = self.userName.text
        user["pass"] = self.passworld.text
        user["mail"] = self.email.text
        user["region"] = self.region.text
        user["question"] = self.question.text
        user["answer"] = self.answer.text
        
        //查询用户是否已经注册
        let query = AVQuery(className: "XBUser")
        query.whereKey("user", equalTo: self.userName.text)
        
        //执行查询
        query.getFirstObjectInBackgroundWithBlock { (object, e) -> Void in
            self.clearAllNotice()
            
            
            //如果查询到相关用户
            if object != nil {
                self.errorNotice("用户已注册")
                self.userName.becomeFirstResponder()
                self.navigationItem.rightBarButtonItem?.enabled = false
                
            } else {
                
                //用户注册
                user.saveInBackgroundWithBlock({ (succeed, error) -> Void in
                    if succeed {
                        self.successNotice("注册成功")
                        self.navigationController?.popViewControllerAnimated(true)
                        
                    } else {
                        print(error)
                    }
                })
                
            }
        }
        
    }
    
}
